#include "NTP.h"

WiFiUDP ntpUDP;

NTPClient ntp(
  ntpUDP, 
  "ntp.aliyun.com",
  8 * 3600
);

void ntp_Init()
{
//  初始化NTP
  ntp.begin();
//  初始化NTP完成
}

uint8_t hour, minute, second;
const char *ntp_GetTime()
{
  ntp.update();

  hour = ntp.getHours();
  minute = ntp.getMinutes();
  second = ntp.getSeconds();

  char timestr[9];
  sprintf(timestr, "%02d:%02d:%02d", hour, minute, second);

  return timestr;
}

const char *ntp_GetDate()
{
  ntp.update();

  time_t epochtime = ntp.getEpochTime();

  struct tm *ptm = gmtime((time_t *)&epochtime);

  int year = ptm->tm_year + 1900;
  int month = ptm->tm_mon + 1;
  int day = ptm->tm_mday;

  char datestr[9];
  sprintf(datestr, "%04d.%02d.%02d", year, month, day);

  return datestr;  
  
}

bool ntpSync()
{
  if(ntp.forceUpdate())
  {
    return true;
  }
  else
  {
//    时间同步失败
    return false;
  }
  
}
